package com.eduction.controller;

import com.eduction.bean.SessionUser;
import com.eduction.common.ReturnCode;
import com.eduction.common.utils.DocToPDFConverter;
import com.eduction.common.utils.DocxToPDFConverter;
import com.eduction.resource.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;


@Controller
@RequestMapping("/views")
public class ViewsController extends BaseController {

    static final Log logger = LogFactory.getLog(CheckController.class);

    @Value("${file_path}")
    private String filePath;


    /*
     * 在线预览图片
     */
    @RequestMapping(value = "/getData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void getData(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {
//        SchoolItemData data = schoolItemDataService.queryById(p_id);
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return ;
        }


        String pathNeed = filePath + path;
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        String fullFileName = pathNeed;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fullFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.debug("图片地址错误");
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("图片output解析错误");
        }
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("图片写入错误");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.debug("图片关闭os异常");
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.debug("图片关闭fis异常");
                }
            }
        }
    }

    /**
     * 数据填报查看pdf
     * 根据路径预览文件
     *
     * @param request
     * @param response
     * @param path
     * @return
     */
    @RequestMapping(value = "/getPdfData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void getPdfData(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {

        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return;
        }

        String pathNeed = filePath + path;
        File srcFile = new File(pathNeed);

        String filename = srcFile.getName();
        String name = null;
        try {
            name = filename.substring(0, filename.indexOf(".")) + ".pdf";
        } catch (Exception e) {
            String[] s = path.split("/");
            path = s[0] + "/" + s[1] + "/" + s[2] + "/" + s[3];
            srcFile = new File(filePath + path);
            String test[];
            test = srcFile.list();
            for (String aTest : test) {
                System.out.println(aTest);
                name = filePath + path + "/" + aTest;
            }
            srcFile = new File(name);
        }
        response.setHeader("Content-Type", "text/plain");
        try {
            response.addHeader("Content-Disposition", "inline;filename=" + new String(name.getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            return toResponse(null, ReturnCode.FAIL, "获取文件异常!");
        }
//        response.addHeader("Content-Length", "" + srcFile.length());
        File file = new File(pathNeed + ".pdf");
        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        FileInputStream fileInputStream = null;
        try {
//            if(!file.exists()){
//                file.createNewFile();
//            }
            inputStream = new FileInputStream(srcFile);
            out = response.getOutputStream();
            if (filename.endsWith(".docx")) {
                DocxToPDFConverter converter = new DocxToPDFConverter(inputStream, out, true, true);
                converter.convert();
                fileInputStream = new FileInputStream(file);
            } else if (filename.endsWith(".doc")) {
                DocToPDFConverter converter = new DocToPDFConverter(inputStream, out, true, true);
                converter.convert();
                fileInputStream = new FileInputStream(file);
            }
            byte[] buffer = new byte[1024];
				        /* while (b != -1){
				            b = inputStream.read(buffer);
				            //4.写到输出流(out)中
				            out.write(buffer,0,b);
				         } */
            int count = 0;
            if (fileInputStream == null) {
                fileInputStream = inputStream;
            }
            while ((count = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        } catch (Exception e) {
            logger.info("获取文件异常", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (out != null) {
                    out.close();
                    out.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 数据填报查看
     * 根据路径预览文件
     *
     * @param request
     * @param response
     * @param path
     * @return
     */
    @RequestMapping(value = "/getWorldData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void getWorldData(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {
//        SchoolItemData data = schoolItemDataService.queryById(p_id);
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return;
        }

        String pathNeed = filePath + path;
        File srcFile = new File(pathNeed);

        String filename = srcFile.getName();
        String name = null;
        try {
            name = filename.substring(0, filename.indexOf(".")) + ".pdf";
        } catch (Exception e) {
            String[] s = path.split("/");
            path = s[0] + "/" + s[1] + "/" + s[2] + "/" + s[3];
            srcFile = new File(filePath + path);
            String test[];
            test = srcFile.list();
            for (String aTest : test) {
                System.out.println(aTest);
                name = filePath + path + "/" + aTest;
            }
            srcFile = new File(name);
        }
        response.setHeader("Content-Type", "application/pdf");
        try {
            response.addHeader("Content-Disposition", "inline;filename=" + new String(name.getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            return toResponse(null, ReturnCode.FAIL, "获取文件异常!");
        }
//        response.addHeader("Content-Length", "" + srcFile.length());
        File file = new File(pathNeed + ".pdf");
        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        FileInputStream fileInputStream = null;
        try {
//            if(!file.exists()){
//                file.createNewFile();
//            }
            inputStream = new FileInputStream(srcFile);
            out = response.getOutputStream();
            if (filename.endsWith(".docx")) {
                XWPFDocument document;
                try (InputStream doc = Files.newInputStream(Paths.get(pathNeed))) {
                    document = new XWPFDocument(doc);
                }
                PdfOptions options = PdfOptions.create();
                try (OutputStream outDocx = Files.newOutputStream(Paths.get(pathNeed + ".pdf"))) {
                    PdfConverter.getInstance().convert(document, out, options);
                }
/*                DocxToPDFConverter converter = new DocxToPDFConverter(inputStream, out, true, true);
                converter.convert();*/
                fileInputStream = new FileInputStream(file);
            } else if (filename.endsWith(".doc")) {
                DocToPDFConverter converter = new DocToPDFConverter(inputStream, out, true, true);
                converter.convert();
                fileInputStream = new FileInputStream(file);
            }
            byte[] buffer = new byte[1024];
				        /* while (b != -1){
				            b = inputStream.read(buffer);
				            //4.写到输出流(out)中
				            out.write(buffer,0,b);
				         } */
            int count = 0;
            if (fileInputStream == null) {
                fileInputStream = inputStream;
            }
            while ((count = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        } catch (Exception e) {
            logger.info("获取文件异常", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (out != null) {
                    out.close();
                    out.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


}